/**
 * Created by Tony on 2017/8/24.
 */
var TableInit = function () {
    var oTableInit = new Object();
    oTableInit.Init = function () {
        $('#shopList').bootstrapTable({
            url:"/shops/getShopList",
            pageSize : 10, // 每页的记录行数（*）
            pageNumber : 1, // 初始化加载第一页，默认第一页
            pagination : true,
            showRefresh : true,
            showToggle : true,
            showColumns : true,
            striped : true, // 是否显示行间隔色
            toolbar : '#toolbar', // 工具按钮用哪个容器
            cache : false, // 是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            method : 'get', // 请求方式（*）
            pageList : [ 10, 25, 50 ], // 可供选择的每页的行数（*）
            sidePagination : "server", // 分页方式：client客户端分页，server服务端分页（*）
            minimumCountColumns : 2, // 最少允许的列数
            height : 500,
            queryParams : oTableInit.queryParams,//查询条件
            ajaxOptions:{'title':1},
            uniqueId:"customer_id", //每一行的唯一标识，一般为主键列
            columns:[  {
                field:'customer_system_no',
                title:'售点系统编号'
            },{
                field:'customer_name',
                title:'店铺名称'
            },{
                field:'customer_contact_name',
                title:'联系人'
            },{
                field:'customer_mobile',
                title:'手机号码'
            },{
                title:'售点照片',
                formatter:function (value, row, index) {
                    return "<a href='" + row.customer_img + "' target='_blank'><img src='" + row.customer_img + "' style='width:80px;height:80px'/></a>";
                }
            },{
                title:'地区',
                field:'city'
            },{
                field:'area',
                title:'区域'
            },{
                field:'address',
                title:'地址'
            },{
                title:'面积',
                field:'shop_size',
            },{
                title:'是否指定经销商',
                field:'specify'
            },{
                title : '状态',
                formatter: function (value, row, index) {
                    if(row.check_status=='1'){
                        return "<font color='red'>合作中</font>";
                    }else if (row.check_status=='-2'){
                        return "已停用";
                    }else if (row.check_status=='2'){
                        return "<font color='green'>合作中+</font>";
                    }
                }
            },{
                field:'channel_type_no',
                title:'渠道',
            },{
                title: '操作',
                field: 'customer_id',
                align: 'center',
                formatter: function (value, row, index) {
                    if(row.check_status=='1'||row.check_status=='2'){
                        var stop = '<a data-toggle="modal" href = "#stopCustomer" mce_href="#" onclick="showStopCustomer(\''+ row.customer_id +'\')">停用</a>';
                        var manager = '<a data-toggle="modal" href = "#managerCustomer" mce_href="#" onclick="managerCustomer(\''+ row.customer_id +'\')">管理</a>';
                        var view = '<a data-toggle="modal" href = "#viewCustomer" mce_href="#" onclick="viewCustomer(\''+ row.customer_id + '\',\''+ row.customer_system_no +'\')">查看</a>';
                        return stop +" "+ manager +" "+ view;
                    }
                    if(row.check_status=='-2'){
                        var release = '<a data-toggle="modal" href = "#releaseCustomer" mce_href="#" onclick="showReleaseCustomer(\''+ row.customer_id +'\')">应用</a>';
                        var manager = '<a data-toggle="modal" href = "#managerCustomer" mce_href="#" onclick="managerCustomer(\''+ row.customer_id +'\')">管理</a>';
                        var view = '<a data-toggle="modal" href = "#viewCustomer" mce_href="#" onclick="viewCustomer(\''+ row.customer_id +'\',\''+ row.customer_system_no +'\')">查看</a>';
                        return release +" "+ manager +" "+ view;
                    }
                    return;
                }
            }

            ]
        });
    };
    //查询参数
    oTableInit.queryParams = function (params) {
        return {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            shop_mobile:$('#shop_mobile').val(),
            city:$("#city option:selected").val(),
            status:$("#status option:selected").val(),
            shop_name:$('#shop_name').val(),
            check_status:$("#check_status option:selected").val(),
            channel_type:$("#channel_type option:selected").val(),
            area:$("#area option:selected").val(),
            customer_system_no:$('#customer_system_no').val(),
            route_id2:$("#route_id2").val(),
            office_address2:$("#office_address2").val(),
        };
    };
    return oTableInit;
}
//时间戳转化
function getLocalTime(nS) {
    return new Date(parseInt(nS)).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}
//初始化
$(document).ready(function(){
    var oTable = new TableInit();
    oTable.Init();
});
//搜索
function search() {
    $("#shopList").bootstrapTable('refresh');
}

//判断是否有指定经销商
function checkMepNo(customer_system_no) {
    debugger;
    $.ajax({
        type:"post",
        url:'/shops/checkMepNo',
        dataType:'json',
        data:{
            'customer_system_no2':customer_system_no,
        },
        sync : false,
        success:function (resp) {
            if(resp.result="true"){
                return true;
            }else {
                return false;
            }
        }
    })
}

//获取地区名字
function getAreaName(area_no) {
    $.ajax({
        type:"post",
        url:"/shops/getAreaNameByAreaNo",
        dataType:"json",
        data:{
            'area_no':area_no,
        },
        success:function (resp) {
            return resp.result;
        }
    })
}

//显示禁封店铺
function showStopCustomer(customer_id){
    $.ajax({
        type: "post",
        url: "/shops/getCustomerInfoById",
        dataType: "json",
        data: {
            'customer_id': customer_id,
        },
        success: function (resp) {
            console.log(resp);
            if (resp.result == 'success') {
                $("#stop-customer-id").val(customer_id);
                $('#stop-customer-system-no').text(resp.customerInfo.customer_system_no);
                $("#stop-customer-name").text(resp.customerInfo.customer_name);
                $("#stop-customer-contacts").text(resp.customerInfo.customer_contact_name);
                $("#stop-customer-address").text(resp.customerInfo.address);
                $("#stop-customer-mobile").text(resp.customerInfo.customer_mobile);
                $("#stop-customer-area").text(resp.customerInfo.area);
                $("#stop-customer-city").text(resp.customerInfo.city);
                $("#stop-channel-type").text(resp.customerInfo.channel_type_no);
                $("#stop-customer-no").text(resp.customerInfo.customer_no || '');
                $("#stop-shop-size").text(resp.customerInfo.shop_size);
                $("#stop-office-address").text(resp.customerInfo.office_address || '');
                $("#stop-route-id").text(resp.customerInfo.route_id || '');
                $("#stop-customer-img").attr('src',resp.customerInfo.customer_img);
                $("#stop-shop-img").attr('href',resp.customerInfo.customer_img)
            }
        }
    })
}

//显示解封店铺页面
function showReleaseCustomer(customer_id) {
    $.ajax({
        type:"post",
        url:"/shops/getCustomerInfoById",
        dataType:"json",
        data:{
            "customer_id":customer_id
        },
        success:function (resp) {
            console.log(resp);
            if(resp.result=='success'){
                $('#release-customer-id').val(customer_id);
                $('#release-customer-system-no').text(resp.customerInfo.customer_system_no);
                $('#release-customer-name').text(resp.customerInfo.customer_name);
                $('#release-customer-contacts').text(resp.customerInfo.customer_contact_name);
                $('#release-customer-mobile').text(resp.customerInfo.customer_mobile);
                $('#release-customer-address').text(resp.customerInfo.address);
                $("#release-customer-area").text(resp.customerInfo.area);
                $("#release-customer-city").text(resp.customerInfo.city);
                $("#release-channel-type").text(resp.customerInfo.channel_type_no);
                $("#release-customer-no").text(resp.customerInfo.customer_no || '');
                $("#release-shop-size").text(resp.customerInfo.shop_size);
                $("#release-office-address").text(resp.customerInfo.office_address || '');
                $("#release-route-id").text(resp.customerInfo.route_id || '');
                $("#release-customer-img").attr('src',resp.customerInfo.customer_img);
                $("#release-shop-img").attr('href',resp.customerInfo.customer_img)
            }
        }

    })
}

//查看店铺
function viewCustomer(customer_id,customer_system_no){
    $.ajax({
        type:'post',
        url:'/shops/getCustomerInfoById',
        dataType:'json',
        data:{
            "customer_id":customer_id,
            "customer_system_no":customer_system_no,
        },
        success:function (resp) {
            console.log(resp);
            if(resp.result=='success'){
                $('#view-customer-id').val(customer_id);
                $('#view-customer-system-no').text(resp.customerInfo.customer_system_no);
                $('#view-customer-name').text(resp.customerInfo.customer_name);
                $('#view-customer-contacts').text(resp.customerInfo.customer_contact_name);
                $('#view-customer-mobile').text(resp.customerInfo.customer_mobile);
                $('#view-customer-address').text(resp.customerInfo.address);
                $("#view-customer-area").text(resp.customerInfo.area);
                $("#view-customer-city").text(resp.customerInfo.city);
                $("#view-channel-type").text(resp.customerInfo.channel_type_no);
                $("#view-customer-no").text(resp.customerInfo.customer_no || '');
                $("#view-shop-size").text(resp.customerInfo.shop_size);
                $("#view-office-address").text(resp.customerInfo.office_address || '');
                $("#view-route-id").text(resp.customerInfo.route_id || '');
                $("#view-customer-img").attr('src',resp.customerInfo.customer_img);
                $("#view-shop-img").attr('href',resp.customerInfo.customer_img)
                $('#specified_mep_no').text(resp.customerInfo.specified_mep_no || '');
            }
        }
    })
}

//显示管理页面
function managerCustomer(customer_id){
    $.ajax({
        type:'post',
        url:"/shops/getCustomerInfoById",
        dataType:"json",
        data:{
            "customer_id":customer_id
        },
        success:function (resp) {
            console.log(resp);
            if (resp.result == 'success') {
                $('#manager-customer-id').val(resp.customerInfo.customer_id);
                $('#customer_no').val(resp.customerInfo.customer_no);
                $('#office_address').val(resp.customerInfo.office_address);
                $('#route_id').val(resp.customerInfo.route_id);
            }
        }
    })
}

//管理店铺
function updateManagerCustomer(){
    var customer_id = $('#manager-customer-id').val();
    var customer_no = $('#customer_no').val();
    var office_address = $('#office_address').val();
    var route_id = $('#route_id').val();
    var customer_sub_channel_no = $('#customer_sub_channel_no').val();
    var consumer_sub_channel_no = $('#consumer_sub_channel_no').val();
    $.ajax({
        type:'post',
        url:'/shops/updateManagerCustomer',
        dataType:'json',
        data:{
            'customer_id':customer_id,
            'customer_no':customer_no,
            'office_address':office_address,
            'route_id':route_id,
            'customer_sub_channel_no':customer_sub_channel_no,
        },
        success:function (resp) {
            if(resp.result = 'success'){
                alertTips("管理成功！");
                search();
                $('#managerCustomer').click();
            }else {
                alertTips("系统异常！");
            }
        }
    })
}

//禁封店铺
function stopCustomer() {
    debugger;
    var customer_id = $("#stop-customer-id").val();
    var check_status = -2;
    $.ajax({
        type:"post",
        url:"/shops/updateCheckStatus",
        dataType:"json",
        data:{
            'customer_id':customer_id,
            'check_status':check_status,
        },
        success:function (resp) {
            if(resp.result=='success'){
                alertTips("禁封成功！");
                search();
                $("#stopCustomer").click();
            }else{
                alertTips("系统异常！");
            }
        }
    })
}

//解封店铺
function releaseCustomer() {
    debugger;
    var customerId = $('#release-customer-id').val();
    var check_status=-2;
    if($('#release-shenmei-id').html()==""||$('#release-office-address').html()==""||$('#release-route-id').html()==""){
        check_status=1;
    }else {
        check_status=2;
    }
    $.ajax({
        type:'post',
        url:'/shops/updateCheckStatus',
        dataType:'json',
        cache : false,
        data:{
            'customer_id':customerId,
            'check_status':check_status,
        },
        success:function (resp) {
            if(resp.result='success'){
                alertTips("解封成功！");
                search();
                $('#releaseCustomer').click();
            }else {
                alertTips("系统异常！");
            }
        }
    })
}

//根据选择的城市获取分区
function getArea(){
    var area = document.getElementById("area");
    var a_length = area.options.length;
    if(a_length>0){
        for(var i=0;i<a_length;i++){
            area.options.remove(0);
        }
    }
    var city = document.getElementById("city");
    var c_value = city.value;
    var areaDetail = [
        ["虹口区","静安区","闵行区","浦东新区","普陀区","新黄浦区","徐汇区","杨浦区","闸北区","长宁区","宝山区","崇明区","奉贤区","嘉定区","金山区","青浦区","松江区"],
        ["崇川区","港闸区","通州区","海安县","海门市","启东市","如东县","如皋市"],
        ["常熟市","昆山市","江阴市","太仓市","张家港市"],
        ["南湖区","秀洲区","海宁市","海盐县","嘉善县","平湖市","桐乡市"],
        ["沧浪区","虎丘区","金阊区","平江区","苏州工业园区","相城区","吴中区","吴江市"],
        ["北塘区","滨湖区","崇安区","惠山区","南长区","无锡市新区","锡山区","宜兴市"]
    ]
    if(c_value==0){
        addOptions("","请选择所在地区");
    }
    for(var j=1;j<7;j++){
        if(c_value==j){
            addOptions("","全部");
            for(var i=0;i<areaDetail[j-1].length;i++){
                addOptions(areaDetail[j-1][i],areaDetail[j-1][i]);
            }
        }
    }
}

//添加下拉框的选项
function addOptions(val,txt){
    var opt = document.createElement("option");
    opt.text = txt;
    opt.value = val;
    area.options.add(opt);
}

//显示导入页面
function showImportTable(){
    var el=document.getElementById('showImportTable');
    el.click();
}
//显示导入loading
function showImportLoading() {
    var el=document.getElementById('loading');
    el.click();
}
//隐藏导入loading
function hideImportLoading() {
    $('#import-loading').click();
}

function importShop(){
    var fileUrl= $('#upload_file_url').val();
    var filename = $('#upload_file_name').html();
    if(checkIsNull(fileUrl)){
        alertTips("请先上传需要导入的Excel文件！");
        return false;
    }
    showImportLoading();
    $.ajax({
        type:"post",
        url:"/shops/importShopInfo",
        dataType:"json",
        data:{
            'fileUrl':fileUrl,
            'filename':filename
        },
        success:function (resp) {
            hideImportLoading();
            console.log(resp);
            if(resp.result2==""){
                alertTips("已导入推荐经销商信息！其中"+resp.successCount+"个成功！"+resp.failCount+"个失败！"+resp.result);
            }else{
                alertTips("已导入推荐经销商信息！其中"+resp.successCount+"个成功！"+resp.failCount+"个失败！"+resp.result + "其中店铺编号为" + resp.result2 + "的店铺数据不存在！");
            }
            search();
            $('#upload-form').click();
        }
    })
}

//导出店铺
function exportShop(){
    var city = $('#city option:selected').val();
    var area = $('#area option:selected').val();
    var shop_mobile = $('#shop_mobile').val();
    var customer_system_no = $('#customer_system_no').val();
    var channel_type = $('#channel_type option:selected').val();
    var check_status = $('#check_status option:selected').val();
    var route_id = $('#route_id2').val();
    var office_address = $('#office_address2').val();
    $.ajax({
        type:'post',
        url:'/shops/exportShopInfo',
        dataType:'json',
        data:{
            "city":city,
            "area":area,
            "shop_mobile":shop_mobile,
            "channel_type":channel_type,
            "check_status":check_status,
            "route_id2":route_id,
            "office_address2":office_address,
            "customer_system_no":customer_system_no,
        },
        success:function (resp) {
            return success;
        }
    })
}


function checkIsNull(value) {
    return value == "" || value == undefined || value == null;
}

